package forum.dao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import forum.bean.OrganizacaoBean;

public class OrganizacaoDAO implements Serializable {

	public OrganizacaoBean get() {
		try {
			SessionFactory sessionFactory = Sessao.getSessionFactory();
			Session session = sessionFactory.openSession();
			
			List<OrganizacaoBean> lista = session.getNamedQuery("organizacao").list();
			
			session.close();
			
			if (lista.size() > 0) {
				return lista.get(0);
			}
		} catch (Exception exception) {
			exception.printStackTrace();
		}
		return null;
	}
	
	public boolean adicionar(OrganizacaoBean organizacaoBean) {
		try {
			SessionFactory sessionFactory = Sessao.getSessionFactory();
			Session session = sessionFactory.openSession();
			Transaction transaction = session.beginTransaction();
			
			this.removeAll();
			
			session.save(organizacaoBean);
			
			transaction.commit();
			session.close();
			
			return true;
		} catch (Exception exception) {
			exception.printStackTrace();
		}
		
		return false;
	}
	
	public void removeAll() {
		try {
			SessionFactory sessionFactory = Sessao.getSessionFactory();
			Session session = sessionFactory.openSession();
			Transaction transaction = session.beginTransaction();
			
			session.createSQLQuery("SELECT * FROM FORUM.SP_REMOVE_ORGANIZACAO()").list();
			
			transaction.commit();
			session.close();
			
		} catch (Exception exception) {
			exception.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("Terminou");
		new OrganizacaoDAO().get();
		
	}
}
